package org.misty.seckill.exception;

import org.misty.seckill.util.ServletUtil;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(BindException.class)
  @ResponseBody
  public List<ObjectError> validationHandler(BindException e) {
    return e.getAllErrors();
  }

  @ExceptionHandler(AuthorizationException.class)
  @ResponseBody
  public String authorizationHandler(AuthorizationException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    if (e.isSignOut() && !ServletUtil.isAjaxRequest(request)) {
      response.sendRedirect("/login.html");
    }
    return e.getMessage();
  }

  @ExceptionHandler(ApplicationException.class)
  @ResponseBody
  public String messageHandler(ApplicationException e) {
    return e.getMessage();
  }
}
